//
//  PreferentialInformationViewController.m
//  CPICMobileServiceApp
//
//  Created by lizhiwei on 13-2-4.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "PreferentialInformationViewController.h"
#import "Config.h"
#import "UIImageView+WebCache.h"
#import "PreferentialInfoTableViewCell.h"
#import "RCAlertViewUtil.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "IFServiceEvaluation.h"
#import "AppDelegate.h"

@interface PreferentialInformationViewController ()

@end

@implementation PreferentialInformationViewController
@synthesize searchField;
@synthesize InfoSerachBar;
@synthesize Tableview;
@synthesize ListContent;
@synthesize progress;
@synthesize strServerType;
@synthesize strservicepoint;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = @"优惠信息";
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        ADD_TITLE_NAMEITEM(@"优惠信息");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        ADD_TITLE_NAMEITEM(@"优惠信息");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        ADD_TITLE_NAMEITEM(@"优惠信息");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }
    
    
    //增加搜索控件
    InfoSerachBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 41)];
    InfoSerachBar.delegate = self;
    
    //下面三行可以改变SearchBar的默认颜色
    UIView *segment = [InfoSerachBar.subviews objectAtIndex:0];
    [segment removeFromSuperview];
    InfoSerachBar.backgroundColor = [UIColor lightGrayColor];
    
    //下面两行设置：当选中SearchBar的时候键盘最下方键的类型
    searchField = [[InfoSerachBar subviews]lastObject];
    [searchField setReturnKeyType:UIReturnKeySearch];
    
    InfoSerachBar.barStyle = UIBarStyleDefault;
    InfoSerachBar.keyboardType = UIKeyboardTypeDefault;
    InfoSerachBar.placeholder = @"";
    
    InfoSerachBar.userInteractionEnabled = YES;
    //显示书的按钮
    InfoSerachBar.showsBookmarkButton = YES;
    //[self.view addSubview:InfoSerachBar];
    //[InfoSerachBar release];
    
    //添加UITableview
    Tableview = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 45, self.view.frame.size.width, self.view.frame.size.height-44)];
	Tableview.delegate = self;
	Tableview.dataSource = self;
    
    Tableview.opaque = NO;
    Tableview.backgroundView = nil;
    Tableview.autoresizingMask = UIViewContentModeTop;
    Tableview.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    //[Tableview reloadData];
	[self.view addSubview:Tableview];
    [Tableview release];
    
    ListContent = [[NSMutableArray alloc] init];
	[ListContent addObjectsFromArray:[NSArray arrayWithObjects:@"投保车险送免费救援服务", @"车险报价送油卡", @"注册会员免费送代驾服务一次", nil]];
    
    IpageNo=1;
    arrData=[[NSMutableArray alloc]init];
    
    if (_refreshHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.Tableview.bounds.size.height, self.view.frame.size.width, self.Tableview.bounds.size.height)];
		view.delegate = self;
		[self.Tableview addSubview:view];
		_refreshHeaderView = view;
		[view release];
    }
    //  update the last update date
	[_refreshHeaderView refreshLastUpdatedDate];
    
    [self setRequest];
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    myDelegate.bPreferentialInformation=FALSE;
    
    [self setEvaluationRequest];
}
-(void) ClickCallOutBtn
{
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    if (myDelegate.bPreferentialInformation==FALSE) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        if ([Flag isEqualToString:@"0"])
        {
            [self IFServiceEvaluation];
            Flag = @"1";
        }
        else
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}

-(void)setEvaluationRequest
{
    NSLog(@"==================");
    NSString *serviceid =@"30201";
    NSString *servicename =@"优惠信息";
    IFServiceEvaluation *ifserviceevaluation =[[IFServiceEvaluation alloc]initView:serviceid withserviceName:servicename];
    [ifserviceevaluation setIfServiceEvaluationRequest];
    [ifserviceevaluation setHidden:YES];
    [self.view addSubview:ifserviceevaluation];
    [ifserviceevaluation release];
}
-(void) IFServiceEvaluation
{
     NSString *serviceid =@"30201";
     NSString *servicename =@"优惠信息";
    NSUserDefaults *myDefaults=[NSUserDefaults standardUserDefaults];
    if ([myDefaults stringForKey:serviceid]) {
        NSString *strEvaluate=[myDefaults stringForKey:serviceid];
        if ([strEvaluate isEqualToString:@"1"]) {
                        AddServiceEvaluationViewController *serviceevluation = [[AddServiceEvaluationViewController alloc]initView:serviceid withserviceName:servicename];
                        [[AppDelegate app].unc pushViewController:serviceevluation animated:YES];
                        [serviceevluation release];
        }
        else
        {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }
    else
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
#pragma UISearchBarDelegate

-(BOOL) searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}

-(void) searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
}

-(BOOL) searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

-(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    //显示取消的按钮
    InfoSerachBar.showsCancelButton = YES;
    NSLog(@"开始编辑了");
}

-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
}

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchField resignFirstResponder];
    //隐藏取消的按钮
    InfoSerachBar.showsCancelButton = NO;
}

-(void) searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchField.text = @"";
    [searchField resignFirstResponder];
    //隐藏取消的按钮
    InfoSerachBar.showsCancelButton = NO;
}

#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrData count];
}

- (CGFloat)tableView:(UITableView *)atableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *Identifier=@"Identifier";
    PreferentialInfoTableViewCell *cell=(PreferentialInfoTableViewCell *)[Tableview dequeueReusableCellWithIdentifier:Identifier];
    if (cell==nil)
    {
        cell=[[[PreferentialInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.lblTitle.font = [UIFont systemFontOfSize:15.0];
    NSMutableDictionary *dictData=[arrData objectAtIndex:indexPath.row];
    cell.lblTitle.text=[dictData valueForKey:@"title"];
    NSString *imgURL=[dictData valueForKey:@"imgUrl"];
    imgURL=[NSString stringWithFormat:@"%@%@",Image_Url,imgURL];
    imgURL=[imgURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [cell.imgViewShort setImageWithURL:[NSURL URLWithString:imgURL] placeholderImage:[UIImage imageNamed:@"placeholder"]];

	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
      
    NSString *strCodeId=[[arrData objectAtIndex:indexPath.row]valueForKey:@"offersId"];
    PreferentialInformationDetailViewController *pidViewCtrl= [[PreferentialInformationDetailViewController alloc] initView:strCodeId];
    [self.navigationController pushViewController:pidViewCtrl animated:YES];
    [pidViewCtrl setRequest];
    [pidViewCtrl release];
}

- (void)viewDidUnload
{
    _refreshHeaderView=nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)setRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=30201";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    NSNumber *PageNo=[NSNumber numberWithInt:IpageNo];
    [dicRequest setObject:PageNo forKey:@"pageNo"];
    NSNumber *PageSize=[NSNumber numberWithInt:10];
    [dicRequest setObject:PageSize forKey:@"pageSize"];
    //[dicRequest setObject:@"" forKey:@"userAccount"];
    if (strServerType.length==0) {
        [dicRequest setObject:@"" forKey:@"servertype"];
    }else
    {
        [dicRequest setObject:strServerType forKey:@"servertype"];
    }
    if (strservicepoint.length==0) {
        [dicRequest setObject:@"" forKey:@"servicepoint"];
    }else
    {
        [dicRequest setObject:strservicepoint forKey:@"servicepoint"];
    }
 
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod= [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"30201" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseFail:)];
    [request setDidFinishSelector:@selector(ResonseSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        //[NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    Flag=@"0";
    if (!showProgress)
    {
      [progress removeFromSuperview];
       progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictOfferList=[dictResponse valueForKey:@"offersList"];
    NSMutableArray *myArrData=[dictOfferList valueForKey:@"data"];
    for (int i=0; i<[myArrData count]; i++) {
        NSMutableDictionary *dictItem=[myArrData objectAtIndex:i];
        [arrData addObject:dictItem];
    }
    NSLog(@"%@",arrData);
    [Tableview reloadData];
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}



#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.Tableview];
	
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	
	[_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	
	[self reloadTableViewDataSource];
	[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:3.0];
    IpageNo=IpageNo+1;
    [self setRequest];
	
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}


-(void)dealloc
{
    _refreshHeaderView = nil;
    [arrData release];
    [super dealloc];
}


@end
